package com.visikard.asynctask;

import android.os.AsyncTask;
import android.os.Handler;

import com.visikard.application.UIMessage;
import com.visikard.response.BaseResponse;

public abstract class BaseTask extends AsyncTask<Object, Object, Object> {

	private static final int MAX_PARAMS = 100;

	protected Handler mUIHandler;
	protected boolean mIsShowProgress;
	protected Object[] mParams;

	abstract protected boolean handleResult(Object result);

	abstract protected Object doBackgroundWork(Object... params);

	public BaseTask(Handler handler) {
		mUIHandler = handler;
		mIsShowProgress = true; // by default showing progress
	}

	public BaseTask(Handler handler, boolean isShowProgress) {
		mUIHandler = handler;
		mIsShowProgress = isShowProgress;
	}

	public boolean setParam(Object param, int pos) {
		if (pos > MAX_PARAMS)
			return false;
		if (mParams == null) {
			mParams = new Object[] { MAX_PARAMS };
		}
		mParams[pos] = param;
		return true;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (mIsShowProgress) {
			mUIHandler.sendEmptyMessage(UIMessage.MSG_SHOW_DIALOG);
		}
	}

	@Override
	protected final Object doInBackground(Object... params) {
		if (mParams != null)
			return doBackgroundWork(mParams);
		return doBackgroundWork(params);
	}

	@Override
	protected final void onPostExecute(Object result) {

		if (!handleResult(result)) {
			BaseResponse response = (BaseResponse) result;
			if (response != null) {
				switch (response.getErrorCode()) {
					case BaseResponse.NETWORK_ERROR:
						mUIHandler.sendEmptyMessage(UIMessage.MSG_NETWORK_ERROR);
						break;
					case BaseResponse.UNKNOWN_ERROR: // unknown error
						mUIHandler.sendEmptyMessage(UIMessage.MSG_UNKNOW_ERROR);
						break;
				}
			}
		}

		if (mIsShowProgress) {
			mUIHandler.sendEmptyMessage(UIMessage.MSG_DISMISS_DIALOG);
		}
		super.onPostExecute(result);
	}

	@Override
	protected void onCancelled() {
		if (mIsShowProgress) {
			mUIHandler.sendEmptyMessage(UIMessage.MSG_DISMISS_DIALOG);
		}
		super.onCancelled();
	}
}
